<?php
class UserRoleService
{
    private $type = 'user';
    private $uid;
    private $uuid;
    private $userRoleModel;
    private $userModel;

    function __construct($uid, $uuid)
    {
        $this->uid              =   $uid;
        $this->uuid             =   $uuid;
        $this->type             =   $uid ? 'user' : 'guest';
        $this->userRoleModel    =   new UserRoleModel();
        $this->userModel        =   new UserModel();
    }

    /**
     * 获取用户角色
     * @return array|object
     */
    public function getUserRole()
    {
        $result = $this->userRoleModel->getRoleInfo($this->type, $this->uid, $this->uuid);
        return $this->rebuildUserRoleData($result);
    }

    /**
     * 修改用户角色信息
     * @param $info
     * @return array|object
     */
    public function setUserRole($info)
    {
        $role = $this->userRoleModel->getRoleInfo($this->type, $this->uid, $this->uuid);
        if (empty($role))
        {
            $result = $this->userRoleModel->initRole($this->type, $info);
        }else{
            $result = $this->userRoleModel->updateRoleInfo($this->type, $info);
        }

        $this->syncUpdateUserInfo($info['gender']);
        if (empty($result)) return false;

        return $this->getUserRole();
    }

    /**
     * 同步修改用户性别
     * @param $sex
     * @return bool
     */
    private function syncUpdateUserInfo($sex)
    {
        if (empty($this->uid) || !in_array(strval($sex), array('0', '1')))
        {
            return false;
        }

        $userService = new UserService();
        $user = $userService->getUserInfo($this->uid, 0);
        if ($user && $user['sex'] == 2)
        {
            $this->userModel->setUserInfo(array('uid' => $this->uid, 'account' => 'aaaaaaa', 'sex' => intval($sex)));
            $userService->updateUserCache($this->uid, array('sex' => strval($sex)));
        }

        if (AC::$errorNo){
            AC::$errorNo = '';
        }
        return true;
    }

    /**
     * 组装输出数据
     * @param $info
     * @return array|object
     */
    private function rebuildUserRoleData($info)
    {
        if (empty($info))
        {
            return (Object) array();
        }

        $result = array(
            "uid"       =>  strval(intval($info['uid'])),
            "uuid"      =>  strval($info['uuid']),
            "gender"    =>  strval(intval($info['gender'])),
            "role"      =>  strval(intval($info['role'])),
            "schedules" =>  $info['schedules'] ? json_decode($info['schedules']) : array(),
            "settings"  =>  $info['settings'] ? json_decode($info['settings']) : array(),
            "update_at" =>  intval($info['update_at']),
            "create_at" =>  intval($info['create_at'])
        );

        return $result;
    }
}